﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using webApi;
using YYS.Controllers;

namespace YYS.Controllers
{
    public partial class wxController : ControlerEx
    {
        public virtual System.Web.Mvc.ActionResult ToResult(YYS.ResultModel model)
        {
            var htm = getResultHtm(model);
            if (htm != null) return Redirect(htm);
            return RedirectToAction("Result", model);
        }
        public static void RegisterBundles(System.Web.Optimization.BundleCollection bundles)
        {
            bundles.Add(new System.Web.Optimization.ScriptBundle("~/Content/wx/index").Include("~/Views/wx/index.js").WithLastModifiedToken());
            bundles.Add(new System.Web.Optimization.ScriptBundle("~/Content/wx/login").Include("~/Views/wx/login.js").WithLastModifiedToken());
        }

        // GET: wx
        [HttpGet]
        [CompressHtml]
        public ActionResult go()
        {
            var code = Request.QueryString["code"].xTrim();
            var userid = Request.QueryString["userid"].xTrim();
            
            //if (!string.IsNullOrWhiteSpace(code) && string.IsNullOrWhiteSpace(userid))
            //{
            //    var login = YYS.Controllers.HomeController.WxLogin(code);
            //    if (login.errcode != 0)
            //    {
            //        return ToResult(new YYS.ResultModel() { IsPart = 1, Icon = 5, Msg = "登录失败：" + login.errmsg });
            //    }
            //    userid = login.openid;
            //}
            //return ToResult(new YYS.ResultModel() { IsPart = 1, Icon = 0, Msg = "加载中，请稍后...", AutoURL = Url.Action("go", "wx", new { state = "userinfo", userid = 123 }), AutoTimeout = 3 });

            //if (string.IsNullOrWhiteSpace(userid))
            //{

            //    return ToResult(new YYS.ResultModel() { IsPart = 1, Icon = 0, Msg = "您尚未登录，请先登录。", AutoURL = Url.Action("login", "wx", new { state = "login", userid = userid }), AutoTimeout = 3 });
            //}
            //if (user.HasError)
            //{
            //    return ToResult(new YYS.ResultModel() { IsPart = 1, Icon = 0, Msg = user.Error, AutoURL = Url.Action("login", "wx", new { state = "login", userid = userid }), AutoTimeout = 3 });
            //}
            return View("~/Views/wx/index.cshtml");
        }

        [HttpGet]
        [CompressHtml]
        public ActionResult login()
        {
            return View("~/Views/wx/login.cshtml");
        }

        public static string Sha1(string text)
        {
            System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            byte[] dataToHash = enc.GetBytes(text);
            byte[] dataHashed = sha.ComputeHash(dataToHash);
            string hash = BitConverter.ToString(dataHashed).Replace("-", "");
            return hash.ToLower();
        }
        #region JsSDK
        [HttpGet]
        public string auth()
        {
            var timestamp = Request.QueryString["timestamp"].xTrim();
            var nonce = Request.QueryString["nonce"].xTrim();
            var signature = Request.QueryString["signature"].xTrim();
            var echostr = Request.QueryString["echostr"].xTrim();

            var dic = new Dictionary<string, string>();
            dic["timestamp"] = timestamp;
            dic["nonce"] = nonce;
            dic["token"] = "yangys";
            string sha1 = "";

            dic = dic.ToDictionary(o => o.Key, p => p.Value);

            foreach (var s in dic)
            {
                sha1 += string.Format("{0}", s.Value);
            }
            //sha1 = sha1.TrimEnd('&');
            var newsignature = Sha1(sha1);
            if (newsignature == signature) return echostr;
            return "无效参数";
        }
        public class accesstoken
        {
            public string expires_in { get; set; }
            public string access_token { get; set; }
        }
        [HttpPost]
        public JsonResult jsSDK()
        {
            var url = Request.Form["url"].xTrim().Split('#')[0];
            if (string.IsNullOrWhiteSpace(url)) return backJson(1, "无效参数.url");

            try
            {
                System.Web.Helpers.AntiForgery.Validate();
            }
            catch (Exception ex)
            {
                return backJson(1, ex.Message + ".Authorization.Token");
            }
            string Appid = DefaultValue.AppID_WX;
            string AppSecret = DefaultValue.AppSecret_WX;
            var path = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={Appid}&secret={AppSecret}";
            var data = HttpGetByWebRequest(path, System.Text.Encoding.UTF8, 100);
            var json = data.xConvertJsonToObject<accesstoken>();
            var timestamp = DateTime.Now.xToTimeStamp().xTrim();
            var nonceStr = Xcode.API.xNoncestr(16);

            var dic = new Dictionary<string, string>();
            dic["jsapi_ticket"] = json.access_token;
            dic["timestamp"] = timestamp;
            dic["noncestr"] = nonceStr;
            dic["url"] = url;

            string sha1 = "";

            dic = dic.ToDictionary(o => o.Key, p => p.Value);

            foreach (var s in dic)
            {
                sha1 += string.Format("{0}={1}&", s.Key, s.Value);
            }
            sha1 = sha1.TrimEnd('&');
            var signature = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sha1, "SHA1").ToLower();

            return backJson(0, null, new
            {
                appId = Appid,
                timestamp = timestamp,
                nonceStr = nonceStr,
                signature = signature,
                sha1 = sha1
            });
        }

        public string createMenu()
        {
            string Appid = DefaultValue.AppID_WX;
            string AppSecret = DefaultValue.AppSecret_WX;
            var path = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={Appid}&secret={AppSecret}";
            var data = HttpGetByWebRequest(path, System.Text.Encoding.UTF8, 100);
            var json = data.xConvertJsonToObject<accesstoken>();

            var url = $"https://api.weixin.qq.com/cgi-bin/menu/create?access_token={json.access_token}";
            //使用JS0N字符品构建菜单
            string menuJson = "{\"button\":[{\"name\":\"Dotnet专栏\",\"sub_button\":[{\"type\":\"view\",\"name\":\"关于我\",\"url\":\"https://blog.csdn.net/Hakim2214\"},{\"type\":\"view\",\"name\":\"微信开发\",\"url\":\"https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html\"}]},{\"name\":\"测试\",\"sub_button\":[{\"type\":\"view\",\"name\":\"运维百科\",\"url\":\"https://blog.csdn.net/Hakim2214\"},{\"type\":\"view\",\"name\":\"在线考试\",\"url\":\"http://sfmes.rjtx.net:55291/MobileApp/index.html\"}]}]}";
            System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            httpWebRequest.Method = "POST";
            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(menuJson);
            httpWebRequest.ContentType = "application/json; charset=utf-8";//
            httpWebRequest.ContentLength = System.Text.Encoding.UTF8.GetByteCount(menuJson);//data为json字符串
            System.IO.Stream stream = httpWebRequest.GetRequestStream();
            stream.Write(postBytes, 0, postBytes.Length);
            stream.Close();//发送完毕，接受返回值
            var response = httpWebRequest.GetResponse();
            System.IO.Stream streamResponse = response.GetResponseStream();
            System.IO.StreamReader streamRead = new System.IO.StreamReader(streamResponse);
            String responseString = streamRead.ReadToEnd();
            return responseString;
        }
        #endregion

        #region 公众号登录保存openid 或者 登出
        [HttpPost]
        public ActionResult wxLogin()
        {
            var openId = Request.Form["openId"].xTrim();//<>null 退出
            var wx_openId = Request.Form["wx_openId"].xTrim();
            var account = Request.Form["account"].xTrim();
            var pwd = Request.Form["pwd"].xTrim();

            if (string.IsNullOrWhiteSpace(openId))
            {
                if (string.IsNullOrWhiteSpace(account)) return backJson(1, "账号不能为空");
                if (string.IsNullOrWhiteSpace(pwd)) return backJson(1, "密码不能为空");
                if (string.IsNullOrWhiteSpace(wx_openId))return backJson(1, "公众号openId不能为空");
            };
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.Exec, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_wxLogin";
            db.IsProc = true;
            db.AddParameter("@account", SqlDbType.NVarChar, account, 50);
            db.AddParameter("@pwd", SqlDbType.NVarChar, pwd, 50);
            db.AddParameter("@wx_openId", SqlDbType.NVarChar, wx_openId, 50);
            db.AddParameter("@openId", SqlDbType.NVarChar, openId, 50);
            db.NeedOutError = true;
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            //TimeSpan slidingExpirationTime = TimeSpan.FromMinutes(300); // 例如30分钟
            //CacheHelper.AddLogin("openId", data["openId"].ToString(), DateTimeOffset.UtcNow.Add(slidingExpirationTime));
            return backJson(0, null);
        }
        #endregion 公众号登录保存openid

        #region 微信内下载文件引导打开浏览器
        [HttpGet]
        [CompressHtml]
        public ActionResult wxDownload()
        {
            return View("~/Views/wx/wxDownload.cshtml");
        }
        #endregion
    }
}